package cj.web.lkg.controllers;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Base64;
import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.ReturnUUID;
import cj.web.lkg.dao.AppUserDAO;
import cj.web.login.controllers.BaseController;
import cj.web.util.SendTemplateSMSUtil;

/**
 * 我的接口，其中包含用户中心、登录、等接口
 * @author Administrator
 *
 */
@Path("/my")
public class MyController extends BaseController{

	private static Logger logger = Logger.getLogger(MyController.class.getName());
	
	@Autowired
	private AppUserDAO appuserDao;
	
	/**
	 * 第三方登录后修改设备与第三方关联
	 * @param devicesId
	 * @param type		0:weixin	1:weibo		2:QQ	3:第三方登录
	 * @param nickname
	 * @param photo
	 * @param loginUUid	登录返回回来的ID号
	 * @return
	 */
	@Get("loginUp")
	public String loginUp(@Param("devicesId") String devicesId,@Param("type") String type,
			@Param("nickname") String nickname,@Param("photo") String photo,@Param("loginUUid") String loginUUid) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String weixinuuid ="0";
		String weibouuid ="0";
		String qquuid ="0";
		String accountlogin="0";
		String wxid ="";
		String qqid ="";
		String sinawbid ="";
		String account ="";
		String typeCode ="";
		if("0".equals(type)){
			weixinuuid="1";
			weibouuid ="0";
			qquuid ="0";
			wxid=loginUUid;
			typeCode="weixin";
		}else if("1".equals(type)){
			weixinuuid="0";
			weibouuid ="1";
			qquuid ="0";
			sinawbid=loginUUid;
			typeCode="weibo";
		}else if("2".equals(type)){
			weixinuuid="0";
			weibouuid ="0";
			qquuid ="1";
			qqid=loginUUid;
			typeCode="qq";
		}else if("3".equals(type)){
			weixinuuid="0";
			weibouuid ="0";
			qquuid ="0";
			account=loginUUid;
			typeCode="account";
		}
		
		appuserDao.upLoginByDevicesId(devicesId, weixinuuid, photo, Base64.getBase64(nickname), 
				qquuid, weibouuid, wxid, qqid, sinawbid, accountlogin, account);
		int size = appuserDao.queryAppDevicesAndUid(devicesId, loginUUid);
		if(size==0)
		{
			appuserDao.createAppDevicesAndUid(devicesId, loginUUid, photo, Base64.getBase64(nickname),typeCode);
		}
		
		return "@"+jo.toString();	
	}
	
	/**
	 * 登出
	 * @param devicesId
	 * @return
	 */
	@Get("loginOut")
	public String loginOut(@Param("devicesId") String devicesId) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		appuserDao.upLoginOutByDevicesId(devicesId, "0", "", "", "0", "0", "0");
		
		return "@"+jo.toString();	
	}
	
	/**
	 * 个人中心
	 * @param devicesId
	 * @return
	 */
	@Get("showUc")
	public String showUc(@Param("devicesId") String devicesId) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> reps = appuserDao.queryAppUserByDevicesId(devicesId);
		
		jo.put("data", returnAppUser(reps));
		return "@"+jo.toString();	
	}
	
	/**
	 * 发送验证码
	 * @param phone	手机号
	 * @return
	 */
	@Get("createLoginToken")
	public String createLoginToken(@Param("phone") String phone) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String token= ReturnUUID.getRandomNum();
		
		//调用短信平台
		String rep = SendTemplateSMSUtil.sendSMS(phone, "91560", token, "1");
//		String rep = Constants.returnObj.returnFlag_true;
		if(rep.equals(Constants.returnObj.returnFlag_true))
		{
			appuserDao.updateToken(phone);
			appuserDao.createToken(phone, token);
		}
		else
		{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();	
	}
	
	/**
	 * 帐号登陆
	 * @param devicesId	设备ID
	 * @param account	帐号
	 * @param token		验证码
	 * @return
	 */
	@Get("accountLogin")
	public String accountLogin(@Param("devicesId") String devicesId,@Param("account") String account,@Param("token") String token) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		int tokenSzie = appuserDao.queryToken(account, token);
		if(tokenSzie!=0){
			appuserDao.upLoginByDevicesId(devicesId, "0", "", Base64.getBase64(account), "0", "0", "", "", "","1",account);
			
			int size = appuserDao.queryAppDevicesAndUid(devicesId, account);
			
			if(size==0){
				appuserDao.createAppDevicesAndUid(devicesId, account, "", Base64.getBase64(account),"account");
			}
			
			jo.put("account", account);
			appuserDao.updateToken(account);
			jo.put("returnCode", Constants.returnObj.returnCode.code_1);
		}else{
			jo.put("returnCode", Constants.returnObj.returnCode.code_2);
		}
		
		return "@"+jo.toString();	
	}
	
	/**
	 * 修改头像
	 * @param uuid
	 * @param name
	 * @return
	 */
	@Get("upMyPhoto")
	public String upMyPhoto(@Param("uuid") String uuid,@Param("phone") String photo) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		appuserDao.upMyPhotoByUUID(uuid, photo);
		appuserDao.upAppPhotoByUUID(uuid, photo);
		return "@"+jo.toString();	
	}
	
	/**
	 * 修改名称
	 * @param uuid
	 * @param name
	 * @return
	 */
	@Get("upMyName")
	public String upMyName(@Param("uuid") String uuid,@Param("name") String name) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		appuserDao.upMyNameByUUID(uuid, name);
		appuserDao.upAppNameByUUID(uuid, name);
		return "@"+jo.toString();	
	}
	
	/**
	 * 我的评论
	 * @param devicesId
	 * @return
	 */
	@Get("pllis")
	public String pllis(@Param("devicesId") String devicesId,@Param("start") int start,@Param("length") int length) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		List<Map> apuser = appuserDao.queryAppUserByDevicesId(devicesId);
		if(apuser.size()>0)
		{
			int weixinuuid = Integer.parseInt(apuser.get(0).get("weixinuuid").toString());
			int qquuid = Integer.parseInt(apuser.get(0).get("qquuid").toString());
			int weibouuid = Integer.parseInt(apuser.get(0).get("weibouuid").toString());
			int accountlogin = Integer.parseInt(apuser.get(0).get("accountlogin").toString());
			
			String wxid = apuser.get(0).get("wxid")==null?"":apuser.get(0).get("wxid").toString();
			String qqid = apuser.get(0).get("qqid")==null?"":apuser.get(0).get("qqid").toString();
			String sinawbid = apuser.get(0).get("sinawbid")==null?"":apuser.get(0).get("sinawbid").toString();
			String account = apuser.get(0).get("account")==null?"":apuser.get(0).get("account").toString();
			
			//回复用户名称修改为第三方登录ID
			String replyName = devicesId;
			if(weixinuuid==1){
				//微信登录
				replyName=wxid;
			}else if(qquuid==1){
				//QQ登录
				replyName=qqid;
			}else if(weibouuid==1){
				//微博登录
				replyName=sinawbid;
			}else if(accountlogin==1){
				//微博登录
				replyName=account;
			}
			
			List<Map> reps = appuserDao.queryCommentsByUserId(replyName,start,length);
			int totalszie = appuserDao.queryCommentsByUserIdSize(replyName);
			jo.put("data", reps);
			jo.put("total", totalszie);
		}
		else
		{
			jo.put("data", "");
			jo.put("total", 0);
		}
		
		return "@"+jo.toString();	
	}
	
	/**
	 * 我的收藏
	 * @param devicesId
	 * @return
	 * @throws ParseException 
	 */
	@Get("sclis")
	public String sclis(@Param("devicesId") String devicesId,@Param("start") int start,@Param("length") int length) throws ParseException {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> apuser = appuserDao.queryAppUserByDevicesId(devicesId);
		if(apuser.size()>0)
		{
			int weixinuuid = Integer.parseInt(apuser.get(0).get("weixinuuid").toString());
			int qquuid = Integer.parseInt(apuser.get(0).get("qquuid").toString());
			int weibouuid = Integer.parseInt(apuser.get(0).get("weibouuid").toString());
			int accountlogin = Integer.parseInt(apuser.get(0).get("accountlogin").toString());
			
			String wxid = apuser.get(0).get("wxid")==null?"":apuser.get(0).get("wxid").toString();
			String qqid = apuser.get(0).get("qqid")==null?"":apuser.get(0).get("qqid").toString();
			String sinawbid = apuser.get(0).get("sinawbid")==null?"":apuser.get(0).get("sinawbid").toString();
			String account = apuser.get(0).get("account")==null?"":apuser.get(0).get("account").toString();
			
			//回复用户名称修改为第三方登录ID
			String userName = devicesId;
			if(weixinuuid==1){
				//微信登录
				userName=wxid;
			}else if(qquuid==1){
				//QQ登录
				userName=qqid;
			}else if(weibouuid==1){
				//微博登录
				userName=sinawbid;
			}else if(accountlogin==1){
				//微博登录
				userName=account;
			}
			
			List<Map> reps = appuserDao.queryCollectById(userName,start,length);
			
			for(Map news:reps)
			{
				List<Map> newObj = appuserDao.queryNewsById(Integer.parseInt(news.get("newsId").toString()));
				
				if(newObj.size()>0)
				{
					if(newObj.get(0).get("releaseAt") != null && !"".equals(newObj.get(0).get("releaseAt").toString())){//时间格式化 去掉从数据库中查出来的小数点及小数点后的0
						String releaseAt = DateUtils.formatDateStr(newObj.get(0).get("releaseAt").toString(), DateUtils.DATE_FULL_STR);
						String releaseAtG = DateUtils.formatDateStr(newObj.get(0).get("releaseAt").toString(), DateUtils.DATE_SMALL_STR);
						news.put("releaseAtMinNumber", DateUtils.getBetweenMinNumber(releaseAt,DateUtils.getNowTime()));//发布时间
						news.put("releaseAt", releaseAtG);
					}
					
					//缩率图
					String carouselImage = newObj.get(0).get("carouselImage")==null?"":newObj.get(0).get("carouselImage").toString();
					if(carouselImage !=null && !"".equals(carouselImage))
					{
						String carouselImages[] = carouselImage.split("/");
						news.put("carouselImage", imgPath+carouselImages[0]+"/s_"+carouselImages[1]);//缩率图
					}
					else
					{
						news.put("carouselImage", "");//缩率图
					}
					news.put("type", newObj.get(0).get("type"));
					news.put("abstractInfor", newObj.get(0).get("abstractInfor"));
					news.put("pvNum", newObj.get(0).get("pvNum"));
					news.put("praiseNum", newObj.get(0).get("praiseNum"));
					news.put("commentsNum", newObj.get(0).get("commentsNum"));
					news.put("forwardNum", newObj.get(0).get("forwardNum"));
					news.put("collectNum", newObj.get(0).get("collectNum"));
				}
				else
				{
					news.put("type", "");
					news.put("carouselImage", "");
					news.put("abstractInfor", "");
					news.put("releaseAt", "");
					news.put("pvNum", 0);
					news.put("praiseNum", 0);
					news.put("commentsNum", 0);
					news.put("forwardNum", 0);
					news.put("collectNum", 0);
				}
				
			}
			
			int totalszie = appuserDao.queryCollectByIdSize(userName);
			jo.put("data", reps);
			jo.put("total", totalszie);
		}
		else
		{
			jo.put("data", "");
			jo.put("total", 0);
		}
		
		return "@"+jo.toString();	
	}
	
	/**
	 * 删除收藏
	 * @param scid
	 * @return
	 */
	@Get("delSC")
	public String delSC(@Param("scid") int scid) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		appuserDao.delCollectById(scid);
		return "@"+jo.toString();	
	}
	
	/**
	 * 我的问
	 * @param devicesId
	 * @return
	 */
	@Get("myQuelis")
	public String myQuelis(@Param("devicesId") String devicesId,@Param("start") int start,@Param("length") int length) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> apuser = appuserDao.queryAppUserByDevicesId(devicesId);
		if(apuser.size()>0)
		{
			int userId = Integer.parseInt(apuser.get(0).get("id").toString());
			String photo = apuser.get(0).get("photo")==null?"":apuser.get(0).get("photo").toString();
			List<Map> dataReps = new ArrayList<Map>();
			//我的问
			List<Map> myQues= appuserDao.queryMyQueById(userId,start,length);
			//我的问size
			int myQueTotal = appuserDao.queryMyQueByIdSize(userId);
			for(Map myq:myQues)
			{
				//别人的回答
				List<Map> myQueAnsls= appuserDao.queryMyQueAnsById(Integer.parseInt(myq.get("id").toString()),0,3);
				
				for(Map obj:myQueAnsls)
				{
					List<Map> appuser = appuserDao.queryAppUserById(Integer.parseInt(obj.get("replyUserId").toString()));
					obj.put("createAt", DateUtils.getBetweenMinNumber(obj.get("createAt").toString()
							,DateUtils.getNowTime()));//发布时间
					obj.put("replyUserPhoto", appuser.get(0).get("photo")!=null?appuser.get(0).get("photo").toString():"");//回答人
				}
			
				Map dataRep = new HashMap();
				dataRep.put("qid", myq.get("id").toString());
				dataRep.put("question", myq.get("msg").toString());
				dataRep.put("photo", photo);//提问人
				dataRep.put("ansDatas", myQueAnsls);
				
				dataReps.add(dataRep);
			}
			
			jo.put("data", dataReps);
			jo.put("total", myQueTotal);
		}
		else
		{
			jo.put("data", "");
			jo.put("total", 0);
		}
		
		return "@"+jo.toString();	
	}
	
	/**
	 * 删除我的问
	 * @param scid
	 * @return
	 */
	@Get("delMyQue")
	public String delMyQue(@Param("qid") int qid) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		appuserDao.delMyQueById(qid);
		return "@"+jo.toString();	
	}
	
	/**
	 * 我的答
	 * @param devicesId
	 * @return
	 */
	@Get("myAnslis")
	public String myAnswerlis(@Param("devicesId") String devicesId,@Param("start") int start,@Param("length") int length) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		List<Map> apuser = appuserDao.queryAppUserByDevicesId(devicesId);
		if(apuser.size()>0)
		{
			int userId = Integer.parseInt(apuser.get(0).get("id").toString());
			String photo = apuser.get(0).get("photo")==null?"":apuser.get(0).get("photo").toString();
			List<Map> reps = appuserDao.queryMyAnsById(userId,start,length);
			
			for(Map obj:reps)
			{
				obj.put("createAt", DateUtils.getBetweenMinNumber(obj.get("createAt").toString()
						,DateUtils.getNowTime()));//发布时间
				List<Map> appuser = appuserDao.queryAppUserById(Integer.parseInt(obj.get("userId").toString()));
				obj.put("photo", appuser.get(0).get("photo")!=null?appuser.get(0).get("photo").toString():"");//提问人
				obj.put("replyUserPhoto", photo);//回答人
			}
			
			int totalszie = appuserDao.queryMyAnsByIdSize(userId);
			jo.put("data", reps);
			jo.put("total", totalszie);
		}
		else
		{
			jo.put("data", "");
			jo.put("total", 0);
		}
		
		return "@"+jo.toString();	
	}
	
	/**
	 * 删除我的答
	 * @param scid
	 * @return
	 */
	@Get("delMyAns")
	public String delMyAns(@Param("aid") int aid) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		appuserDao.delMyAnsById(aid);
		return "@"+jo.toString();	
	}
	
	/**
	 * 返回用户信息
	 * @param reps
	 * @return
	 */
	private Map returnAppUser(List<Map> reps)
	{
		Map rep = new HashMap();
		for(Map objRep:reps)
		{
			rep.put("id", objRep.get("id"));
			rep.put("devicesId", objRep.get("devicesId"));
			rep.put("phone", objRep.get("phone")==null?"":objRep.get("phone").toString());
			rep.put("account", objRep.get("account")==null?"":objRep.get("account").toString());
			rep.put("name", objRep.get("name")==null?"":Base64.getFromBase64(objRep.get("name").toString()));
			
			//缩率图
			String photo = objRep.get("photo")==null?"":objRep.get("photo").toString();
			if(photo !=null && !"".equals(photo))
			{
				rep.put("photo", photo);
			}
			else
			{
				rep.put("photo", "");//缩率图
			}
			
			rep.put("state", objRep.get("state"));
			
			rep.put("weixinuuid", objRep.get("weixinuuid")==null?"":objRep.get("weixinuuid").toString());
			rep.put("qquuid", objRep.get("qquuid")==null?"":objRep.get("qquuid").toString());
			rep.put("weibouuid", objRep.get("weibouuid")==null?"":objRep.get("weibouuid").toString());
		}
		return rep;
	}
}
